/*
 * SHOPTNT 版权所有。
 * 未经许可，您不得使用此文件。
 * 官方地址：www.shoptnt.cn
 */
package cn.shoptnt.api.buyer.goods;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.shoptnt.model.goods.vo.BrandVO;
import cn.shoptnt.model.goods.vo.CategoryVO;
import cn.shoptnt.service.goods.BrandManager;
import cn.shoptnt.service.goods.CategoryManager;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * 商品分类控制器
 *
 * @author fk
 * @version v2.0
 * @since v7.0.0 2018-03-15 17:22:06
 */
@RestController
@RequestMapping("/goods/categories")
@Api(tags= "商品分类相关API")
public class CategoryBuyerController {

    @Autowired
    private CategoryManager categoryManager;

    @Autowired
    private BrandManager brandManager;

    @ApiOperation(value = "首页等商品分类数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parent_id", value = "分类id，顶级为0", required = true, dataType = "int", dataTypeClass = Integer.class, paramType = "path")
    })
    @GetMapping(value = "/{parent_id}/children")
    public List<CategoryVO> list(@PathVariable("parent_id") Long parentId) {
        //先获取全部分类信息集合
        List<CategoryVO> catTree = categoryManager.listAllChildren(parentId);
        //再获取全部关联了分类的品牌信息集合
        List<BrandVO> brandList = this.brandManager.getAllBrandCategory();

        //通过循环将品牌信息放入关联的分类信息中
        if (brandList != null && brandList.size() != 0) {
            //将关联了分类的品牌信息集合拆分成以分类ID为key的Map
            Map<Long, List<BrandVO>> brandMap = brandList.stream().collect(Collectors.groupingBy(BrandVO::getCategoryId));
            //循环分类将品牌信息放入
            for (CategoryVO cat : catTree) {
                cat.setBrandList(brandMap.get(cat.getCategoryId()));
            }
        }
        return catTree;
    }
}
